package com.qst.service.impl;

import com.qst.pojo.vo.DashboardStatsVO;
import com.qst.repository.UserRepository;
import com.qst.service.DashboardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 仪表板服务实现类
 */
@Service
public class DashboardServiceImpl implements DashboardService {

    private static final Logger logger = LoggerFactory.getLogger(DashboardServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    @Override
    public DashboardStatsVO getDashboardStats() {
        DashboardStatsVO stats = new DashboardStatsVO();

        // 获取统计卡片数据
        stats.setStatsCard(getStatsCard());

        // 获取最新订单
        stats.setRecentOrders(getRecentOrders());

        // 获取站点状态
        stats.setStationStatus(getStationStatus());

        return stats;
    }

    /**
     * 获取统计卡片数据
     */
    private DashboardStatsVO.StatsCard getStatsCard() {
        DashboardStatsVO.StatsCard card = new DashboardStatsVO.StatsCard();

        try {
            // 统计总用户数
            Long totalUsers = userRepository.count();
            card.setTotalUsers(totalUsers);

            // 统计站点数
            String stationCountSql = "SELECT COUNT(*) FROM stations";
            Integer totalStations = jdbcTemplate.queryForObject(stationCountSql, Integer.class);
            card.setTotalStations(totalStations != null ? totalStations : 0);

            // 统计订单数
            String orderCountSql = "SELECT COUNT(*) FROM orders";
            Long totalOrders = jdbcTemplate.queryForObject(orderCountSql, Long.class);
            card.setTotalOrders(totalOrders != null ? totalOrders : 0L);

            // 统计总收入
            String revenueSql = "SELECT SUM(total_amount) FROM orders WHERE status = 'completed'";
            BigDecimal totalRevenue = jdbcTemplate.queryForObject(revenueSql, BigDecimal.class);
            card.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);

        } catch (Exception e) {
            logger.error("获取统计卡片数据失败", e);
            card.setTotalUsers(0L);
            card.setTotalStations(0);
            card.setTotalOrders(0L);
            card.setTotalRevenue(BigDecimal.ZERO);
        }

        return card;
    }

    /**
     * 获取最新订单
     */
    private List<DashboardStatsVO.RecentOrder> getRecentOrders() {
        List<DashboardStatsVO.RecentOrder> orders = new ArrayList<>();

        try {
            String sql = "SELECT o.id, o.order_no, u.real_name as customer_name, " +
                    "o.total_amount, o.status, o.created_at " +
                    "FROM orders o " +
                    "LEFT JOIN users u ON o.customer_id = u.id " +
                    "ORDER BY o.created_at DESC " +
                    "LIMIT 5";

            List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

            for (Map<String, Object> row : rows) {
                DashboardStatsVO.RecentOrder order = new DashboardStatsVO.RecentOrder();
                order.setId((Integer) row.get("id"));
                order.setOrderNo((String) row.get("order_no"));
                order.setCustomerName((String) row.get("customer_name"));
                order.setTotalAmount((BigDecimal) row.get("total_amount"));
                order.setStatus((String) row.get("status"));
                
                Object createdAt = row.get("created_at");
                if (createdAt != null) {
                    order.setCreateTime(createdAt.toString());
                }

                orders.add(order);
            }

        } catch (Exception e) {
            logger.error("获取最新订单失败", e);
        }

        return orders;
    }

    /**
     * 获取站点状态
     */
    private List<DashboardStatsVO.StationStatus> getStationStatus() {
        List<DashboardStatsVO.StationStatus> stations = new ArrayList<>();

        try {
            String sql = "SELECT id, name, current_load, capacity, status " +
                    "FROM stations " +
                    "ORDER BY current_load DESC " +
                    "LIMIT 5";

            List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

            for (Map<String, Object> row : rows) {
                DashboardStatsVO.StationStatus station = new DashboardStatsVO.StationStatus();
                station.setId((Integer) row.get("id"));
                station.setName((String) row.get("name"));
                station.setCurrentLoad((Integer) row.get("current_load"));
                station.setCapacity((Integer) row.get("capacity"));
                station.setStatus((String) row.get("status"));

                stations.add(station);
            }

        } catch (Exception e) {
            logger.error("获取站点状态失败", e);
        }

        return stations;
    }
}


